#include "SpriteObject.h"
#include <exception>
#include <stdio.h>

extern GameState game_state;

u8 SpriteObject::next_id[] = {0,0};

SpriteObject::SpriteObject(OamState * oam, SpriteSize size, SpriteColorFormat colorFormat) {
	u8 id = next_id[oam == &oamMain ? 0 : 1]++;

	this->id = id;
	gfxStartAddress = oamAllocateGfx(oam, size, colorFormat);
	oamSet(oam, id, 0, 0, 0, 0, size, colorFormat, gfxStartAddress, 0, false,
		false, false, false, false);
	sprite_entry = &oam->oamMemory[id];
	engine = oam;
}

int get_sprite_memory_offset(coord * coords) {
	return coords->x % 8 + coords->y % 8 * 8 + coords->x / 8 * 64 + coords->y/8 * 128;
}

u8 stylus_is_over(touchPosition * touchPos, SpriteEntry * sprite) {
	return (touchPos->px >= sprite->x && touchPos->px <= sprite->x + 15)
				&& (touchPos->py >= sprite->y && touchPos->py <= sprite->y + 15);
}

coord get_stylus_position_relative_to_sprite(touchPosition * touchPos, SpriteEntry * sprite) {
	coord pos;
	pos.x = touchPos->px - sprite->x;
	pos.y = touchPos->py - sprite->y;
	return pos;
}

u8 SpriteObject::stylus_is_over_opaque(touchPosition * touchPos, SpriteEntry * sprite) {
	if (stylus_is_over(touchPos, sprite)) {
		u8 * pixel = (u8 *)oamGetGfxPtr(engine, sprite->gfxIndex);
		coord pos = get_stylus_position_relative_to_sprite(touchPos, sprite);
		int offset = get_sprite_memory_offset(&pos);
		printf("palette index: %u\n", pixel[offset]);
		
		return pixel[offset] != 0;
	}
	
	return 0;
}

void SpriteObject::stylusDown(touchPosition & touch) {
	if (stylus_is_over_opaque(&touch, sprite_entry)) {
		game_state = DRAG;
		printf("Sprite %d is dragging\n", id);
		is_dragged = true;
	}
}

void SpriteObject::stylusUp(touchPosition & touch) {
	if (is_dragged) {
		game_state = PUZZLE;
		is_dragged = false;
		printf("Sprite %d released\n", id);
	}
}

u16 * SpriteObject::get_gfx_start_address() {
	return gfxStartAddress;
}

void SpriteObject::set_position(coord coords) {
	sprite_entry->x = coords.x;
	sprite_entry->y = coords.y;
}